import java.util.Random;
import java.util.concurrent.*;
/**
 * 高并发随机数ThreadLocalRandom与Random分析
 * Random存在性能缺陷，主要元婴是要不断的计算新的种子和更新原种子，使用CAS方法，不同的线程采用同一个random对象，
 * 不同线程在生成随机数是，采用自旋操作，高并发的情况，降低性能
 * 下造成大量的线程自选，而只有一个线程会更新成功
 * ThreadLocalRandom 采用ThreadLocal，每一个线程都是用自己的种子去进行计算下一个种子，规避CAS在并发下的问题
 *
 */
public class ThreadLocalRandomTest1 {
    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        CountDownLatch countDownLatch = new CountDownLatch(100);
        CyclicBarrier bar = new CyclicBarrier(100);
        ExecutorService exec = Executors.newFixedThreadPool(100);
        for (int i = 0; i < 100; i++) {
            exec.submit(new RandomDemo1Runner(bar,"thread"+i,countDownLatch));
        }
        countDownLatch.await();
        long use = System.currentTimeMillis() - start;
        System.out.println(" main is over..." + use);
        exec.shutdown();
    }
}

class RandomDemo1Runner implements Runnable {
    private CyclicBarrier barrier;
    private String name;
    private CountDownLatch cd;

    RandomDemo1Runner(CyclicBarrier barrier, String name, CountDownLatch cd) {
        this.barrier = barrier;
        this.name = name;
        this.cd = cd;
    }

    @Override
    public void run() {
        try {
            System.out.println(name + "准备好了...");
            barrier.await();
            for (int i = 0; i < 10000; i++) {
                ThreadLocalRandom.current().nextInt(50);
            }
            cd.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }

    }


}
